<?php

namespace app\model\oa;

use think\Model;
use think\model\concern\SoftDelete;

/**
 * 新闻模型
 * @package app\model\oa
 */
class News extends Model
{
    use SoftDelete;

    // 表名
    protected $name = 'news';

    // 主键
    protected $pk = 'id';

    // 自动时间戳
    protected $autoWriteTimestamp = true;
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = 'delete_time';

    // 字段类型转换
    protected $type = [
        'id' => 'integer',
        'title' => 'string',
        'content' => 'string',
        'author_id' => 'integer',
        'category_id' => 'integer',
        'status' => 'integer',
        'is_top' => 'integer',
        'is_hot' => 'integer',
        'view_count' => 'integer',
        'like_count' => 'integer',
        'comment_count' => 'integer',
        'cover_image' => 'string',
        'summary' => 'string',
        'tags' => 'string',
        'source' => 'string',
        'source_url' => 'string',
        'publish_time' => 'int',
        'create_time' => 'int',
        'update_time' => 'int',
        'delete_time' => 'int',
    ];

    // 新闻状态常量
    const STATUS_DRAFT = 0;        // 草稿
    const STATUS_PUBLISHED = 1;    // 已发布
    const STATUS_OFFLINE = 2;      // 已下线

    /**
     * 获取状态文本
     */
    public static function getStatusText($status)
    {
        $texts = [
            self::STATUS_DRAFT => '草稿',
            self::STATUS_PUBLISHED => '已发布',
            self::STATUS_OFFLINE => '已下线',
        ];
        return $texts[$status] ?? '未知';
    }

    /**
     * 关联作者
     */
    public function author()
    {
        return $this->belongsTo('app\model\admin\User', 'author_id', 'id');
    }

    /**
     * 关联分类
     */
    public function category()
    {
        return $this->belongsTo('app\model\oa\NewsCategory', 'category_id', 'id');
    }

    /**
     * 获取新闻列表
     */
    public static function getList($params = [])
    {
        $query = self::with(['author', 'category'])->order('create_time', 'desc');

        // 按状态筛选
        if (isset($params['status']) && $params['status'] !== '') {
            $query->where('status', $params['status']);
        }

        // 按分类筛选
        if (!empty($params['category_id'])) {
            $query->where('category_id', $params['category_id']);
        }

        // 按作者筛选
        if (!empty($params['author_id'])) {
            $query->where('author_id', $params['author_id']);
        }

        // 按标题搜索
        if (!empty($params['title'])) {
            $query->where('title', 'like', '%' . $params['title'] . '%');
        }

        // 按内容搜索
        if (!empty($params['content'])) {
            $query->where('content', 'like', '%' . $params['content'] . '%');
        }

        // 按标签搜索
        if (!empty($params['tags'])) {
            $query->where('tags', 'like', '%' . $params['tags'] . '%');
        }

        // 按来源搜索
        if (!empty($params['source'])) {
            $query->where('source', 'like', '%' . $params['source'] . '%');
        }

        // 置顶和热门文章优先
        $query->order('is_top', 'desc')
              ->order('is_hot', 'desc')
              ->order('publish_time', 'desc');

        return $query->paginate($params['limit'] ?? 15);
    }

    /**
     * 获取已发布的新闻
     */
    public static function getPublishedList($params = [])
    {
        $params['status'] = self::STATUS_PUBLISHED;
        return self::getList($params);
    }

    /**
     * 获取置顶新闻
     */
    public static function getTopNews($limit = 5)
    {
        return self::where('is_top', 1)
            ->where('status', self::STATUS_PUBLISHED)
            ->order('publish_time', 'desc')
            ->limit($limit)
            ->select();
    }

    /**
     * 获取热门新闻
     */
    public static function getHotNews($limit = 5)
    {
        return self::where('is_hot', 1)
            ->where('status', self::STATUS_PUBLISHED)
            ->order('view_count', 'desc')
            ->limit($limit)
            ->select();
    }

    /**
     * 获取推荐阅读
     */
    public static function getRecommendNews($limit = 5)
    {
        return self::where('status', self::STATUS_PUBLISHED)
            ->where(function ($query) {
                $query->where('is_hot', 1)->whereOr('is_top', 1);
            })
            ->order('view_count', 'desc')
            ->limit($limit)
            ->select();
    }

    /**
     * 增加浏览次数
     */
    public function incrementViewCount()
    {
        $this->inc('view_count')->update([]);
    }

    /**
     * 增加点赞次数
     */
    public function incrementLikeCount()
    {
        $this->inc('like_count')->update([]);
    }

    /**
     * 增加评论次数
     */
    public function incrementCommentCount()
    {
        $this->inc('comment_count')->update([]);
    }

    /**
     * 发布新闻
     */
    public function publish()
    {
        $this->status = self::STATUS_PUBLISHED;
        $this->publish_time = date('Y-m-d H:i:s');
        $this->save();
    }

    /**
     * 下线新闻
     */
    public function offline()
    {
        $this->status = self::STATUS_OFFLINE;
        $this->save();
    }

    /**
     * 获取标签数组
     */
    public function getTagsArray()
    {
        return $this->tags ? explode(',', $this->tags) : [];
    }

    /**
     * 设置标签
     */
    public function setTagsAttribute($value)
    {
        if (is_array($value)) {
            $this->attributes['tags'] = implode(',', $value);
        } else {
            $this->attributes['tags'] = $value;
        }
    }

    /**
     * 搜索器 - 标题
     */
    public function searchTitleAttr($query, $value)
    {
        $query->where('title', 'like', '%' . $value . '%');
    }

    /**
     * 搜索器 - 内容
     */
    public function searchContentAttr($query, $value)
    {
        $query->where('content', 'like', '%' . $value . '%');
    }

    /**
     * 搜索器 - 状态
     */
    public function searchStatusAttr($query, $value)
    {
        $query->where('status', $value);
    }

    /**
     * 搜索器 - 分类ID
     */
    public function searchCategoryIdAttr($query, $value)
    {
        $query->where('category_id', $value);
    }

    /**
     * 搜索器 - 作者ID
     */
    public function searchAuthorIdAttr($query, $value)
    {
        $query->where('author_id', $value);
    }

    /**
     * 搜索器 - 是否置顶
     */
    public function searchIsTopAttr($query, $value)
    {
        $query->where('is_top', $value);
    }

    /**
     * 搜索器 - 是否热门
     */
    public function searchIsHotAttr($query, $value)
    {
        $query->where('is_hot', $value);
    }

    /**
     * 搜索器 - 标签
     */
    public function searchTagsAttr($query, $value)
    {
        $query->where('tags', 'like', '%' . $value . '%');
    }

    /**
     * 搜索器 - 来源
     */
    public function searchSourceAttr($query, $value)
    {
        $query->where('source', 'like', '%' . $value . '%');
    }

    /**
     * 搜索器 - 发布时间范围
     */
    public function searchPublishTimeAttr($query, $value)
    {
        if (is_array($value) && count($value) == 2) {
            $query->whereBetween('publish_time', $value);
        }
    }

    /**
     * 搜索器 - 创建时间范围
     */
    public function searchCreateTimeAttr($query, $value)
    {
        if (is_array($value) && count($value) == 2) {
            $query->whereBetween('create_time', $value);
        }
    }
}